﻿// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;

    var canvas, context;
    var gameStage;
    var preload;
    var logoScreenImage, logoScreenBitmap;
    var floorImage, floorBitmap;
    var playerIdleImage, playerIdleBitmap;

    var newGame = true;
    var player;
    
    var scaleW = window.innerWidth / 1366;
    var scaleH = window.innerHeight / 768;

    var ghosts = [];
    var ghostSpeed = 1.0;
    var ghostImage, ghostBitmap;
    var timeToAddNewGhost = 0;

    var isGameOver = false;

    var scoreText;
    var playerScore = 0;

    app.onactivated = function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                // TODO: This application has been newly launched. Initialize
                // your application here.
            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }
            args.setPromise(WinJS.UI.processAll());
        }
    };

    // The player class
     function Player() {
             this.positionX = window.innerWidth / 2;
             this.positionY = window.innerHeight / 2;
          
             this.targetX = this.positionX;
             this.targetY = this.positionY;
          
             this.width = playerIdleBitmap.image.width * scaleW;
             this.height = playerIdleBitmap.image.height * scaleH;
         }
     
     function Ghost(gfx) {
              this.positionX = Math.random() * 5000 - 2500;
              this.positionY = Math.random() * 3000 - 1500;
           
              this.setStartPosition = function () {
                      if (this.positionX >= 0 && this.positionX <= window.innerWidth) {
                              this.positionX = -500;
                          }
               
                      if (this.positionY >= 0 && this.positionY <= window.innerHeight) {
                              this.positionY = -500;
                          }
                  }
           
              this.targetX = 0;
              this.targetY = 0;
           
              this.move = function (tX, tY) {
                     this.targetX = tX;
                      this.targetY = tY;
               
                      if (this.targetX > this.positionX) {
                              this.positionX += ghostSpeed;
                          }
                      if (this.targetX < this.positionX) {
                              this.positionX -= ghostSpeed;
                          }
                      if (this.targetY > this.positionY) {
                              this.positionY += ghostSpeed;
                          }
                      if (this.targetY < this.positionY) {
                              this.positionY -= ghostSpeed;
                         }
                  };
           
              this.isCollision = function (playerX, playerY, playerW, playerH) {
                      var centerX = this.positionX + (this.ghostBitmap.image.width * scaleW / 2);
                      var centerY = this.positionY + (this.ghostBitmap.image.height * scaleH / 2);
               
                      if ((centerX >= playerX - playerW / 2) && (centerX < playerX + playerW / 2)) {
                              if ((centerY >= playerY - playerH / 2) && (centerY < playerY + playerH / 2)) {
                                      return true;
                                  }
                          }
               
                      return false;
                  }
           
             this.ghostBitmap = gfx;
     }

    function pointerUp(event) {
             if (newGame) {
                     newGame = false;
                 }
             else {
                 player.targetX = event.x;
                 player.targetY = event.y;
             }
    }
    function pointerDown(event) {
             if (newGame) {
                 }
             else {
                     player.targetX = event.x;
                     player.targetY = event.y;
                 }
         }
      
     function pointerMove(event) {
             if (newGame) {
                 }
             else {
                     player.targetX = event.x;
                     player.targetY = event.y;
                 }
         }

    function initialize() {
             canvas = document.getElementById("gameCanvas");
             canvas.width = window.innerWidth;
             canvas.height = window.innerHeight;
             context = canvas.getContext("2d");
             canvas.addEventListener("MSPointerUp", pointerUp, false);
             canvas.addEventListener("MSPointerMove", pointerMove, false);
             canvas.addEventListener("MSPointerDown", pointerDown, false);
             gameStage = new createjs.Stage(canvas);

             loadContent();
         }
      
    function loadContent() {
        preload = new createjs.PreloadJS();
        preload.onComplete = prepareStage;
        
             var manifest = [
                { id: "logoScreen", src: "images/GFX/LogoScreen.png" },
                { id: "floor", src: "images/GFX/floor.png" },
                { id: "ghost", src: "images/GFX/Ghost.png" },
                { id: "playerIdle", src: "images/GFX/PlayerIdle.png" }
                ];
      
         preload.loadManifest(manifest);

    }

    function prepareStage() {
             logoScreenImage = preload.getResult("logoScreen").result;
             logoScreenBitmap = new createjs.Bitmap(logoScreenImage);
             logoScreenBitmap.scaleX = scaleW;
             logoScreenBitmap.scaleY = scaleH;
             gameStage.addChild(logoScreenBitmap);

             floorImage = preload.getResult("floor").result;
             floorBitmap = new createjs.Bitmap(floorImage);
             floorBitmap.visible = false;
             floorBitmap.scaleX = scaleW;
             floorBitmap.scaleY = scaleH;
             gameStage.addChild(floorBitmap);
             
             playerIdleImage = preload.getResult("playerIdle").result;
             playerIdleBitmap = new createjs.Bitmap(playerIdleImage);
             playerIdleBitmap.visible = false;
             playerIdleBitmap.scaleX = scaleW;
             playerIdleBitmap.scaleY = scaleH;
             gameStage.addChild(playerIdleBitmap);


             scoreText = new createjs.Text("Score: " + playerScore, "30px sans-serif", "yellow");
             scoreText.x = canvas.width / 2 - (scoreText.getMeasuredWidth() * scaleW / 2);
             scoreText.scaleX = scaleW;
             scoreText.scaleY = scaleH;
             scoreText.y = 30 * scaleH;
             scoreText.visible = false;
             gameStage.addChild(scoreText);

             player = new Player();

             createjs.Ticker.setInterval(window.requestAnimationFrame);
             createjs.Ticker.addListener(gameLoop);

             ghostImage = preload.getResult("ghost").result

         }
      
    function gameLoop() {
        update();
        draw();
         }
      
    function update() {
             if (newGame) {
                     logoScreenBitmap.visible = true;
                     playerIdleBitmap.visible = false;
                     floorBitmap.visible = false;
                     scoreText.visible = false;
                 }
             else {
                 if (isGameOver) {
                          isGameOver = false;
                          ghosts.length = 0;
                          gameStage.clear();
                       
                          gameStage.addChild(logoScreenBitmap);
                          gameStage.addChild(floorBitmap);
                          gameStage.addChild(playerIdleBitmap);
                          gameStage.addChild(scoreText);
                       
                          gameStage.update();

                          newGame = true;
                          playerScore = 0;
                      }
                     
                 
                     logoScreenBitmap.visible = false;
                     playerIdleBitmap.visible = true;
                     floorBitmap.visible = true;
                     scoreText.visible = true;

                     playerScore += 1;
                     scoreText.text = ("Score: " + playerScore);

                              if (player.targetX > player.positionX) {
                                      player.positionX += 3;
                                  }
                              if (player.targetX < player.positionX) {
                                      player.positionX -= 3;
                                  }
                              if (player.targetY > player.positionY) {
                                      player.positionY += 3;
                                  }
                              if (player.targetY < player.positionY) {
                                      player.positionY -= 3;
                              }

                              timeToAddNewGhost -= 1;
                              if (timeToAddNewGhost < 0) {
                                       timeToAddNewGhost = 1000
                                       ghosts.push(new Ghost(new createjs.Bitmap(ghostImage)));
                                       ghosts[ghosts.length - 1].setStartPosition();
                                       gameStage.addChild(ghosts[ghosts.length - 1].ghostBitmap);
                              }

                              for (var i = 0; i < ghosts.length; i++)
                            {
                                       ghosts[i].ghostBitmap.x = ghosts[i].positionX;
                                       ghosts[i].ghostBitmap.y = ghosts[i].positionY;
                                       ghosts[i].ghostBitmap.visible = true;
                                       ghosts[i].move(player.positionX, player.positionY);
                                       isGameOver = ghosts[i].isCollision(player.positionX, player.positionY, player.width, player.height);
                                       if (isGameOver)
                                                break;
                              }

                              playerIdleBitmap.x = player.positionX - (player.width / 2);
                              playerIdleBitmap.y = player.positionY - (player.height / 2);
                 }
         }
      
    function draw() {
        gameStage.update();
         }

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. You might use the
        // WinJS.Application.sessionState object, which is automatically
        // saved and restored across suspension. If you need to complete an
        // asynchronous operation before your application is suspended, call
        // args.setPromise().
    };


    document.addEventListener("DOMContentLoaded", initialize, false);


    app.start();
})();
